﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace IslandInterloper.Engine
{
    internal class AvatarCommodity:GameClient
    {
        private string commodity = string.Empty;
        private double units = 0.0;
        public double Units
        {
            get
            {
                return units;
            }
            set
            {
                units = value;
            }
        }
        private double costPerUnit = 0.0;
        public double CostPerUnit
        {
            get
            {
                return costPerUnit;
            }
            set
            {
                costPerUnit = value;
            }
        }
        public double Tonnage
        {
            get
            {
                return Units * Game.Commodities[commodity].TonsPerUnit;
            }
        }
        public double MaximumPurchase(double unitCost)
        {
            double maximumPurchaseByTonnage = (Game.Ships[Game.Avatar.Ship].MaximumTonnage - Game.Avatar.Inventory.TotalTonnage)/Game.Commodities[commodity].TonsPerUnit;
            double maximumPurchaseByCost = Game.Avatar.Inventory[Game.Config.CurrencyCommodity].Units/unitCost;
            return (maximumPurchaseByCost < maximumPurchaseByTonnage) ? maximumPurchaseByCost : maximumPurchaseByTonnage;
        }
        internal AvatarCommodity(Game theGame, string theCommodity)
            : base(theGame)
        {
            commodity = theCommodity;
            units = Game.Commodities[theCommodity].GenerateInventory();
            costPerUnit = 0.0;
        }
        internal AvatarCommodity(Game theGame, XElement element)
            : base(theGame)
        {
            FromXElement(element);
        }
        public void FromXElement(XElement element)
        {
            commodity = element.Name.LocalName;
            units = Utilities.XElementToDouble(element.Element(GameXNames.units));
            costPerUnit = Utilities.XElementToDouble(element.Element(GameXNames.costPerUnit));
        }
        public override XElement ToXElement(XName xName)
        {
            XElement result = new XElement(xName,
                new XElement(GameXNames.units, units.ToString()),
                new XElement(GameXNames.costPerUnit, costPerUnit.ToString())
                );
            return result;
        }
    }
}
